Use Gatsby to create a blog 您所在的位置:网站首页 how to create pages dynamically in gatsby Use Gatsby to create a blog

Use Gatsby to create a blog

2023-03-09 16:03| 来源: 网络整理| 查看: 265

Gatsby is an incredible static site generator that allows you to build a static site using React as a rendering engine, and it really has all the benefits that a modern Web application would expect. It renders dynamic React components as static HTML content by server-side rendering at build time. This means that your users get all the benefits of a static site, such as no JavaScript, search engine friendliness, very fast loading times, and so on, without losing the vibrancy and interactivity that the modern Web has come to expect. Once rendered as static HTML, the client site's React and JavaScript take over and add dynamic content. Gatsby recently released V1.0.0 with a lot of new features. This includes (but is not limited to) the ability to create content queries using GraphQL, integrate with a variety of CMS -- including WordPress, Contentful, Drupal, and more. There is also routing based code distribution for a better user experience. In this post, we'll take an in-depth look at Gatsby and some new features, and create a static blog. Let's get started!

start Install the cli

npm install -g gatsby-cli

Gatsby comes with a great CLI(command line interface) that includes the ability to build a work site and commands to help develop that site.

gatsby new personal-blog cd $_

This command creates the folder personal-blog and then goes to that directory. A development environment is now in place. The Gatsby CLI includes many common development features, such as The Gatsby Build (building a production, statically generated version of a project), Gatsby Develop (starting a hot-loaded Web development server), and more.

We can now begin real development on this site and create a fully functional, modern blog. You usually want to start the local development server using Gatsby Develop to verify the functionality we accomplished in the steps.

Add the necessary plug-ins

Gatsby supports the use of rich plug-ins, many of which are very useful and are written to accomplish common tasks. Plug-ins can be divided into three main categories: functional plug-ins, Source plug-ins, and Transformer plug-ins.

Feature plug-in

Feature plug-ins are used to implement certain features (offline support, generating a sitemap, etc.) or they extend the Gatsby Webpack configuration to add support for Typescript, Sass, etc. For this particular blog post, we wanted a single-page application feel (no page reloading) and the ability to dynamically change the title tag in the Head tag. As mentioned, the Gatsby ecosystem of plug-ins is rich, vibrant, and growing, so often a plug-in that already exists can solve the specific problem you want to solve. To address the features we want for this blog, we will use the following plug-ins:

gatsby-plugin-catch-links Realizing historypushStateAPI to navigate to different pages of your blog without page reloading gatsby-plugin-react-helmet react-helmetIs a kind of permit modificationheadThe tag utility Gatsby statically renders these header tag changes

Use the following command:

`yarn add gatsby-plugin-catch-links gatsby-plugin-react-helmet` Copy the code

We used YARN, but using NPM is also easy: NPM I --save [deps]. After installing these feature plug-ins, we will edit Gatsby -config.js. Gatsby loads the exposed functionality of specified plug-ins at build time.

module.exports = { siteMetadata: { title: `Your Name - Blog`, author: `Your Name`, }, plugins: [ 'gatsby-plugin-catch-links', 'gatsby-plugin-react-helmet', ], } Copy the code

In addition to using YARN install and editing configuration files, you can now edit the site head tag and implement a single-page application without reloading. Now, let's enhance the basic functionality by implementing a source plug-in that loads blog posts from the local file system.

Source plug-in

The source plug-in creates the node, which is then converted to a usable format through a converter plug-in. For example, a typical workflow would normally use the Gatsby - source-Filesystem, which loads files from disk, such as Markdown files, and then specifies a Markdown converter to convert the Markdown to HTML. Since most of the blog content is in Markdown format, let's add the Gatsby - source-Filesystem, similar to our previous steps, we'll install the plug-in and then inject it into our Gatsby -config.js, like this:

`yarn add gatsby-source-filesystem` Copy the code module.exports = { // previous configuration plugins: [ 'gatsby-plugin-catch-links', 'gatsby-plugin-react-helmet', { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/src/pages`, name: 'pages', }, } ] } Copy the code

A little explanation would help here! An Options object can be passed to a plug-in, and we're passing the file system path (where our Markdown file will be located), followed by the name of the source file. Now that Gatsby knows our source files, we can start applying some useful converters to convert these files into usable data!

Converter plug-in

As mentioned earlier, the converter plug-in takes some low-level data formats that aren't currently available in forms (Markdown, JSON, YAML, etc.), and we can use GraphQL queries to convert it to a format that Gatsby understands. The filesystem source plug-in will load file nodes (such as Markdown) from our filesystem, and the Markdown converter will take over and convert them into usable HTML. We will only use a converter plug-in (for Markdown), so let's install it.

gatsby-transformer-remark useremarkThe Markdown parser converts the MD file on disk to HTML. In addition, the converter has the option of using plug-ins to further extend functionality, such as throughgatsby-remark-prismjsTo add syntax highlighting throughgatsby-remark-copy-linked-filesCopy the relevant file specified in Markdown and passgatsby-remark-imagesCompress the image and usesrcsetAdd responsive images and so on.

This process should be familiar by now, and added to the configuration after installation.

`yarn add gatsby-transformer-remark` Copy the code

Edit gatsby - config. Js

module.exports = { // previous setup plugins: [ 'gatsby-plugin-catch-links', 'gatsby-plugin-react-helmet', { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/src/pages`, name: 'pages', }, }, { resolve: 'gatsby-transformer-remark', options: { plugins: [] // just in case those previously mentioned remark plugins sound cool :) } }, ] }; Copy the code

Yo! It seems like there are a lot of Settings, but these plugins will make Gatsby powerful and give us an incredible (but relatively simple!) Development environment. We need a simpler step. All we need to do is create a Markdown file that will contain the content of our first blog post. Let's get started!

Write your first Markdown article

The Gatsby - source-Filesystem plugin we configured earlier wanted our content to be placed in SRC/Pages. Gatsby doesn't have a naming convention, but a typical practice for blog posts is to give folders names like MM-DD-YYYY-title, such as 07-12-2017-Hello-world. Let's create a folder SRC /pages/ 07-12-2017-geing-started and put index.md in it. The content of this Markdown file will be our blog post, written using Markdown (of course!). Here's what it should look like:

-- Path: "/hello-world" date: "2017-07-12T17:12:33.962z" title: "My First Gatsby Post" --- Oooooh-weeee, my first blog post!Copy the code

What is contained in the line? This is called frontMatter, and this part of the content can be used by the React component (e.g. path, date, title, etc.) you can add other data, so you are free to experiment and find the information necessary to implement an ideal blogging system for you to use. It is important to note that path will be used to identify routes when we create pages dynamically to specify pages. In this example, http://localhost:8000/hello-world will be the file path. Now that we've created a blog post with FrontMatter and some content, we can start writing React components that display this data.

Create a React template.

When Gatsby supported the React component for server-side rendering (of strings), we could write our templates using React (and also Preact). We'll create a SRC /templates/blog-post.js file (please create a SRC /templates folder)

import React from 'react'; import Helmet from 'react-helmet'; // import '.. /css/blog-post.css'; // make it pretty! export default function Template({ data // this prop will be injected by the GraphQL query we'll write in a bit }) { const { markdownRemark: post } = data; // data.markdownRemark holds our post data return ( div className="blog-post-container" Helmet title={`Your Blog Name - ${post.frontmatter.title}`} / div className="blog-post" h1{post.frontmatter.title}/h1 div className="blog-post-content" dangerouslySetInnerHTML={{ __html: post.html }} / /div /div ); }Copy the code

Wow, neat! The React component will be rendered as a static HTML string, which will be the basis for our blog navigation. At this point, there is a reasonable amount of confusion and magic that can occur, especially when the PROPS property is injected. What is markdownRemark? Where does this data support come from? Let's answer these questions by writing a GraphQL query to add content to our component.

Write a GraphQL query

Under the Template declaration, we'll add a GraphQL query. It was a very powerful tool for Gatsby. This allows us to easily pick and choose the snippet of data we want to show us for the blog post. Each data selected by our query will be injected through the data properties we specified earlier.

import React from 'react'; import Helmet from 'react-helmet'; // import '.. /css/blog-post.css'; export default function Template({ data }) { const { markdownRemark: post } = data; return ( div className="blog-post-container" Helmet title={`Your Blog Name - ${post.frontmatter.title}`} / div className="blog-post" h1{post.frontmatter.title}/h1 div className="blog-post-content" dangerouslySetInnerHTML={{ __html: post.html }} / /div /div ); } export const pageQuery = graphql` query BlogPostByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") path title } } } `;Copy the code

If you're not familiar with GraphQL, this might seem a little confusing, but we can break it down a bit.

Note: For more information about GraphQL, see Excellent Resource

Query name BlogPostByPath (note: these query names must be unique!) Will be injected into the current path, such as the specific blog post we are looking at. This path will be available as $path in the query. For example, if we look at the blog post we created earlier, the path to the file that will be extracted from the data will be /hello-world. The data is obtained from the injected property, named markdownRemark in the GraphQL query. Each of the attributes we retrieved from the GraphQL query can be found under markdownRemark. For example, to access the converted HTML we would go to data.markdownremark.html to retrieve the data. Of course, our data structure is FrontMatter provided at the beginning of our Markdown file. Each key we define can be injected into the query. At this point, we've installed a bunch of plug-ins to load files from disk and convert Markdown to HTML. We have a separate Markdown file that will be published as a blog. Finally, we have a React template for blog posts and a linked GraphQL query to query blog posts and inject the React template into the queried data. Next: programmatically creating the necessary static pages (and injecting templates) with Gatsby's Node API, let's get started. One thing to note at this point is that the GraphQL query is done at build time. The component is injected with data obtained by the GraphQL query. Unless there is some dynamic processing (logic for componentDidMount, state changes), this component will be pure, HTML generated by the React rendering engine, GraphQL, and Gatsby.

Creating a static page

Gatsby exposed a powerful Node API that allowed for things like dynamic pages (blog post pages!). , extend the Babel or Webpack configuration, modify the nodes or pages created, and so on. This API is written in the gatsby-node.js file, and every export found in this file will be analyzed by Gatsby. Gatsby talked at length about its Node API specification. However, we only care about one particular APIcreatePages in this instance.

const path = require('path'); ​ exports.createPages = ({ boundActionCreators, graphql }) = { const { createPage } = boundActionCreators; ​ const blogPostTemplate = path.resolve(`src/templates/blog-post.js`); } Copy the code

Nothing complicated! We are already using the createPages API (which Gatsby will call at build time with injected parameters). We will also get the path to the blogPostTemplate we created earlier. Finally, we used createPage to activate boundActionCreators, which Gatsby managed internally using Redux. BoundActionCreators was just an action created by Gatsby. For a complete list of all public actions, see the Gatsby documentation. Now we can construct a GraphQL query that will fetch all of our Markdown posts.

Query the article const path = require('path'); exports.createPages = ({ boundActionCreators, graphql }) = { const { createPage } = boundActionCreators; const blogPostTemplate = path.resolve(`src/templates/blog-post.js`); return graphql(`{ allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] } limit: 1000 ) { edges { node { excerpt(pruneLength: 250) html id frontmatter { date path title } } } } }`) .then(result = { if (result.errors) { return Promise.reject(result.errors); }}); }Copy the code

We use GraphQL to get all the Markdown nodes and use them under the GraphQL attribute allMarkdownRemark. Each exposed property (on the node) can be used for queries. We are effectively creating a GraphQL database, which we can then query through page-level GraphQL queries. Note here that the exports.createpages API expects to return a Promise. One of the cool things about this is that the Gatsby plugin-remark plug-in provides some useful data for us to query with GraphQL, such as excerpt (a short snippet of code as a preview), ID (unique identifier for each post), and so on. Now that we have written the query, we have not created the page programmatically (using the createPage action creator). Let's get started!

Create the page const path = require('path'); ​ exports.createPages = ({ boundActionCreators, graphql }) = { const { createPage } = boundActionCreators; ​ const blogPostTemplate = path.resolve(`src/templates/blog-post.js`); ​ return graphql(`{ allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] } limit: 1000 ) { edges { node { excerpt(pruneLength: 250) html id frontmatter { date path title } } } } }`) .then(result = { if (result.errors) { return Promise.reject(result.errors); } ​ result.data.allMarkdownRemark.edges .forEach(({ node }) = { createPage({ path: node.frontmatter.path, component: blogPostTemplate, context: {} // additional data can be passed via context }); }); }); } Copy the code

We now have a GraphQL query for a Promise. Actual posts by path result. Data. AllMarkdownRemark. The edges. We'll use this data to build a page that includes Gatsby. Our GraphQL "shape" is directly reflected in this data object, so when we query in the GraphQL blog post template, every attribute we extract from that query will be available. The createPage API accepts an object that needs to define path and Component properties, as we have done above. In addition, you can use the optional context property to inject data and make it available to the blog post template component by injecting props (various props to see every available prop!). Each time we build Gatsby, createPage will be called and Gatsby will create a static HTML file path according to the FrontMatter we wrote specifically earlier in the post. The GraphQL query data is injected into the React template after Stringified and Parsed. Wow, it's really starting to work! We can then run yarn develop and then open the http://localhost:8000/hello-world to see our first blog post, should be as follows:

At this point, we created a single-page static blog using the React component and a few GraphQL queries. However, this is not a blog! We can't expect users to guess the path of every post, we need to have an index or list page showing each blog post, a short introduction, and a link to the full blog post. You have no idea how easy it was for us to do this with Gatsby, using similar strategies we used in the blog template, such as a React component and a GraphQL query.

Create a blog list

I won't go into detail in this section, because we've done something very similar with our blog template! Look at us, we're already professional Gatsby users at this point! For lists of pages, Gatsby has a specification, and they are placed in the root directory of the filesystem we specify, such as SRC /pages/index.js. If it doesn't exist, create the file and let it run. Also note that any static JavaScript file (exporting a React component!) I get the corresponding static HTML file. For example, we create a SRC/pages/tags. The js file, http://localhost:8000/tags/ will be accessible.

import React from 'react'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; // import '.. /css/index.css'; // add some style if you want! export default function Index({ data }) { const { edges: posts } = data.allMarkdownRemark; return ( div className="blog-posts" {posts .filter(post = post.node.frontmatter.title.length 0) .map(({ node: post }) = { return ( div className="blog-post-preview" key={post.id} h1 Link to={post.frontmatter.path}{post.frontmatter.title}/Link /h1 h2{post.frontmatter.date}/h2 p{post.excerpt}/p /div ); })} /div ); } export const pageQuery = graphql` query IndexQuery { allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) { edges { node { excerpt(pruneLength: 250) id frontmatter { title date(formatString: "MMMM DD, YYYY") path } } } } } `;Copy the code

Ok! We took a similar approach in the blog post template, so this should look very familiar. Again, we export the pageQuery that contains the GraphQL query. Note that we are extracting a slightly different data set, specifically, we are extracting a 250 character summary instead of the full HTML, and we are also formatting drag dates with format strings! GraphQL is pretty elegant. The actual React component is quite trivial, one caveat is that you should always use The Gatsby link when linking to internal content. Gatsby doesn't work if pages aren't routed through the utility. In addition, you can use pathPrefix, which allows the Gatsby web site to be deployed to a non-root domain. This is useful if the blog will be hosted on a Github page. Or hang on /blog. Now it's getting exciting, it feels like we're finally getting there. Now we have a fully functional blog generated by Gatsby, with real content in Markdown, a list of blogs, and the ability to browse within blogs. If you implement Yarn Develop, http://localhost:8000 should display the thumbnail content of each blog post, with each post title linking to the blog post's content. This is a real blog!

Now, the knowledge you gain as you follow this tutorial will enable you to do some incredible things. You can not only use CSS(Styled components!) Make it beautiful, but also make it more powerful by implementing the following features!

Add a tag list and tag query page

Tip:gatsby-node.jsIn the filecreatePagesThe API is useful here, and the previous onefrontmatter Add navigation between specific blog posts (createPages 的 contextAs we explore Gatsby and its apis, you should feel empowered to start taking full advantage of Gatsby's potential. Blogs are just a starting point; Gatsby's rich ecosystem, extensible apis, and advanced query capabilities provide a powerful tool set for building truly incredible high-performance sites.

Now go do something great!

Links @dschau/gatsby-blog-starter-kit The library available to show Gatsby all of the above features @dschau/create-gatsby-blog-post I created a utility and CLI to use in the predefined Gatsby structure andfrontmatter, date, path, etc. Build a blog post. A utility and CLI I created to scaffold out a blog post following the predefined Gatsby structure with frontmatter, date, path, etc. Blog source code My blog source code, it usedgatsby-star-blog-postAnd extends it with a set of features and some more advanced functionality.


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有